<template>
  <div
    class="unitWrapper demo-autocomplete"
    :id="'scroll' + workEnviromentIndex + '-0'"
  >
    <div class="unitTop">
      <div class="unitTitleContainer">
        <div class="unitFlag"></div>
        <div class="unitTitle">工作时间和强度</div>
      </div>
      <div class="saveBtns" v-if="!isSuperToken && false">
        <div class="contentItemEditAndAIBtn AIBtn" @click="aiCreate()">
          <img src="@/assets/detail/AI_white.png" />
          {{ aiCreateStatus ? 'AI正在生成中 . . .' : 'AI生成' }}
        </div>
        <div class="contentItemEditAndAIBtn" @click="handleEditClick">
          <img src="@/assets/detail/edit_white.png" />
          {{ currentEdit ? '退出编辑' : '编辑' }}
        </div>
        <div
          class="contentItemEditAndAIBtn saveEditBtn"
          @click="save()"
          v-if="isAdmin == true && currentEdit"
        >
          <!-- <img src="@/assets/detail/save.png" /> -->
          保存
        </div>
      </div>
    </div>
    <div
      :class="{ unitContent: true, colunmDirection: firstExtendContent.length }"
    >
      <div class="firstItem">
        <div
          :class="{
            itemForDisplay: true,
            inEdit: currentEdit && firstExtendContent.length
          }"
        >
          <div class="firstChildList">
            <div
              class="firstChildItem"
              v-for="(item, index) in hoursData"
              :key="index"
            >
              <img
                :src="getFirstItemImg(item.layerKey)"
                alt=""
                class="firstChildItemImg"
              />
              <div class="firstChildInfo">
                <div class="firstChildDescription">{{ item.description }}</div>
                <el-input
                  v-if="currentEdit"
                  size="mini"
                  class="firstChildInput"
                  v-model="item.editLayerValue"
                  placeholder="输入内容"
                ></el-input>
                <div class="firstChildValue" v-else>{{ item.layerValue }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="itemForEdit" v-if="firstExtendContent.length">
          <div :class="{ editBoxRight: true, inEdit: currentEdit }">
            <div
              v-for="(item, index) in firstExtendContent"
              class="extendsItem"
              :key="index"
            >
              <div v-html="item"></div>
              <div
                class="replaceByOne"
                @click="replaceByOne('first', item)"
                v-if="currentEdit"
              >
                一键替换
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="secondItem">
        <div class="itemForDisplay">
          <span class="editTips" v-show="currentEdit">
            点击图表数字标签可以直接修改数据
          </span>
          <div class="h100" ref="line_echartDom"></div>
        </div>
        <div class="itemForEdit" v-if="secondExtendContent.length">
          <div :class="{ editBoxRight: true, inEdit: currentEdit }">
            <div
              v-for="(item, index) in secondExtendContent"
              class="extendsItem"
              :key="index"
            >
              <div v-html="item"></div>
              <div
                class="replaceByOne"
                @click="replaceByOne('second', item)"
                v-if="currentEdit"
              >
                一键替换
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <websocket ref="child1" @initMessageBack="initMessageBackForFirst" />
    <websocket ref="child2" @initMessageBack="initMessageBackForSecond" />
  </div>
</template>

<script>
import {
  homepageQuestion,
  valueListAnalysis,
  valueLayerValueAnalysis
} from '@/api/position-detail';
import { addLog } from '@/api/position';
import { MessageBox, Message } from 'element-ui';
import Websocket from '@/components/Websocket';
export default {
  name: 'workHoursAndIntensity',
  props: {
    isAdmin: {
      type: Boolean,
      default: true
    },
    isSuperToken: {
      type: Boolean,
      default: false
    },
    positionItemList: {
      type: Array,
      default: () => []
    },
    workEnviromentIndex: {
      type: Number || String,
      default: 1
    }
  },
  data() {
    return {
      aiCreateStatus: false,
      currentEdit: false,
      positionId: '',
      intensityChartData: {
        intensityNameData: [],
        intensityValueData: []
      },
      hoursData: [],
      originChartData: [], //发送保存请求的时候用的。。
      firstExtendContent: [],
      secondExtendContent: [],
      firstMessages: [],
      secondMessages: [],
      firstQuestionId: '',
      secondQuestionId: ''
    };
  },
  mounted() {
    this.positionId = this.$route.query.id;
    this.init();
  },
  watch: {
    positionItemList: {
      handler(newValue, oldValue) {
        if (newValue.length) {
          newValue.forEach((item) => {
            if (item.layerId == 11) {
              this.hoursData = item.data;
              this.firstQuestionId = item.questionId;
            }
            if (item.layerId == 17) {
              //保留一位小数
              this.originChartData = item.data.map((item, index) => {
                item.layerValue = (+item.layerValue).toFixed(1);
                return item;
              });
              item.data.forEach((item) => {
                this.secondQuestionId = item.questionId;
                this.intensityChartData.intensityNameData.push({
                  max: 5,
                  description: item.description,
                  value: item.layerValue
                });
                this.intensityChartData.intensityValueData.push(
                  item.layerValue
                );
              });
            }
            // //console.log("intensityChartData", this.intensityChartData);
            // //console.log("hoursData", this.hoursData);
          });
        }
      },
      immediate: true
    }
  },
  methods: {
    save() {
      this.$confirm('此操作将覆盖原有内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        //保存文字维度的
        const paramsList = [];
        this.hoursData.forEach((item) => {
          paramsList.push({
            id: item.id,
            ylPositionId: this.positionId,
            questionId: item.questionId,
            description: item.description,
            layerKey: item.layerKey,
            layerValue: item.editLayerValue
          });
          this.$set(item, 'layerValue', item.editLayerValue);
        });
        this.updateLayerValue(paramsList, this.hoursData);
        this.firstExtendContent = [];
        this.secondExtendContent = [];
        this.currentEdit = false;
      });
    },
    replaceByOne(flag, val) {
      let questionId = '';
      if (flag == 'first') {
        questionId = this.firstQuestionId;
      } else {
        questionId = this.secondQuestionId;
      }
      const params = {
        questionContent: val.replace(/<br>/g, ' '),
        id: questionId,
        ylPositionId: this.positionId
      };
      valueListAnalysis(params).then((res) => {
        if (res.code == 200) {
          if (flag == 'first') {
            res.data.forEach((item, index) => {
              if (this.hoursData[index]) {
                this.$set(
                  this.hoursData[index],
                  'editLayerValue',
                  item.layerValue
                );
                item.id = this.hoursData[index].id;
              }
            });
          } else {
            this.$confirm('此操作将覆盖原有内容, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.intensityChartData.intensityNameData = [];
              this.intensityChartData.intensityValueData = [];
              res.data.forEach((item) => {
                if (!item.description || !item.layerValue) return;
                this.intensityChartData.intensityNameData.push({
                  max: 5,
                  description: item.description,
                  value: item.layerValue
                });
                this.intensityChartData.intensityValueData.push(
                  item.layerValue
                );
                //替换掉旧数据
                this.originChartData.forEach((oriItem, oriIndex) => {
                  if (oriItem.layerKey == item.layerKey) {
                    oriItem.layerValue = item.layerValue;
                  }
                });
              });
              //还要发送请求给后端保存。。。
              this.updateLayerValue(this.originChartData, this.originChartData);
              // //console.log("打印一下被替换掉之后的数据", this.originChartData);
              this.init();
            });
          }
        } else {
          //console.log("内容解析失败了！请尝试重新生成！");
        }
      });
    },
    updateLayerValue(paramsList, listData) {
      valueLayerValueAnalysis(paramsList).then((res) => {
        if (listData) {
          listData.forEach((item) => {
            this.$set(item, 'layerValue', item.editLayerValue);
          });
        }
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
      });
    },
    handleEditClick() {
      this.hoursData.forEach((item) => {
        this.$set(item, 'editLayerValue', item.layerValue);
      });
      this.currentEdit = !this.currentEdit;
      if (this.currentEdit) {
        this.$message({
          type: 'success',
          message: '点击雷达图的标签可以单个编辑数据',
          offset: 400
        });
      }
    },
    getFirstItemImg(layerKey) {
      switch (layerKey) {
        case 'workHour':
          return 'https://img3.job1001.com/data_center/images/工作时长.svg';
        case 'workSchedule':
          return 'https://img3.job1001.com/data_center/images/工作安排.svg';
        case 'workOvertime':
          return 'https://img3.job1001.com/data_center/images/加班频率.svg';
        case 'workRestTime':
          return 'https://img3.job1001.com/data_center/images/休息时间.svg';
        default:
          break;
      }
    },
    initMessageBackForFirst(res) {
      const msg = res.choices && res.choices[0];
      if (msg.delta.role === 'assistant') {
        return;
      }
      if (msg.finish_reason === 'stop' || msg.finish_reason === 'done') {
        this.loading = false;
        this.currentRole = '';
        this.aiCreateStatus = false;
        let textEl = document.querySelectorAll('.AIBtn');
        textEl.forEach((item) => {
          item.classList.remove('AILoading');
        });
        return;
      }
      if (msg.delta.content) {
        var tempStr = msg.delta.content;
        if (tempStr) {
          tempStr = tempStr.replace(/(\r\n|\n|\r)+/g, '<br>');
        }
        let len = this.firstExtendContent
          ? this.firstExtendContent.length - 1
          : 0;
        this.$set(
          this.firstExtendContent,
          len,
          (this.firstExtendContent[len] += tempStr)
        );
      }
    },
    initMessageBackForSecond(res) {
      const msg = res.choices && res.choices[0];
      if (msg.delta.role === 'assistant') {
        return;
      }
      if (msg.finish_reason === 'stop' || msg.finish_reason === 'done') {
        this.loading = false;
        this.currentRole = '';
        this.aiCreateStatus = false;
        let textEl = document.querySelectorAll('.AIBtn');
        textEl.forEach((item) => {
          item.classList.remove('AILoading');
        });
        return;
      }
      if (msg.delta.content) {
        var tempStr = msg.delta.content;
        if (tempStr) {
          tempStr = tempStr.replace(/(\r\n|\n|\r)+/g, '<br>');
        }
        let len = this.secondExtendContent
          ? this.secondExtendContent.length - 1
          : 0;
        // console.log(
        //   "this.secondExtendContent,len,(this.secondExtendContent[len] += tempStr)",
        //   this.secondExtendContent,
        //   len,
        //   tempStr
        // );

        this.$set(
          this.secondExtendContent,
          len,
          (this.secondExtendContent[len] += tempStr)
        );
      }
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      let indicator = this.intensityChartData.intensityNameData,
        value = this.intensityChartData.intensityValueData;
      const that = this;
      let option = {
        color: ['#4283FF'],
        radar: [
          {
            indicator,
            radius: '50%',
            splitNumber: 5,
            shape: 'circle',
            silent: true,
            triggerEvent: true,
            axisName: {
              formatter: function (value, indicator) {
                const name = indicator.description;
                const realValue = indicator.value;
                return `{a|${name}} {b|${realValue}}`;
              },
              rich: {
                a: {
                  color: '#555',
                  fontSize: 15
                },
                b: {
                  fontFamily: 'D-DIN-PRO-500-Medium',
                  fontWidth: 'bold',
                  color: '#4880FF',
                  fontSize: 24,
                  padding: [0, 0, 0, 6]
                }
              },
              textStyle: {
                color: '#fff'
              }
            },
            axisLine: {
              lineStyle: {
                color: '#B8D6FD',
                width: 0.5
              }
            },
            splitLine: {
              lineStyle: {
                color: [
                  '#E5EEF7',
                  '#E5EEF7',
                  '#E5EEF7',
                  '#E5EEF7',
                  '#E5EEF7',
                  '#B8D4F2'
                ]
              }
            }
          }
        ],
        series: [
          {
            type: 'radar',
            emphasis: {
              lineStyle: {
                width: 4,
                color: '#4283FF'
              }
            },
            data: [
              {
                value,
                areaStyle: {
                  color: new this.$echarts.graphic.RadialGradient(0.5, 0, 1, [
                    {
                      color: 'rgba(0, 78, 255, 0.5)',
                      offset: 0
                    },
                    {
                      color: 'rgba(88, 122, 250, 0.1)',
                      offset: 1
                    }
                  ]),
                  borderColor: '#4283FF'
                },
                itemStyle: {
                  // 设置连接线不可见
                  opacity: 0
                }
              }
            ]
          }
        ]
      };
      option && this.myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.on('click', function (params) {
        if (params.componentType === 'radar' && that.currentEdit) {
          // //console.log("myChart click", params);
          var regex = /\{([a-z])\|([^}]+)\}/g;
          var match;
          match = regex.exec(params.name);
          const nowName = match[2];
          MessageBox.prompt(`请输入${nowName}新的值：`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^(5(\.0)?|[0-4](\.\d)?)$/,
            inputErrorMessage: '输入格式不正确'
          })
            .then(({ value }) => {
              that.handleChartValueChange(nowName, value);
            })
            .catch((e) => {
              //console.log("e", e);

              Message({
                type: 'info',
                message: '取消输入'
              });
            });
        }
      });
    },
    handleChartValueChange(nowName, value) {
      this.originChartData.forEach((item) => {
        if (item.description == nowName) {
          item.layerValue = value;
          this.updateLayerValue(
            [{ ...item, layerValue: value }],
            this.originChartData
          );
          this.intensityChartData.intensityNameData.forEach((item, index) => {
            if (item.description == nowName) {
              item.value = value;
              this.intensityChartData.intensityValueData[index] = value;
              this.myChart.off('click');
              this.init();
            }
          });
        }
      });
    },
    async aiCreate() {
      if (this.aiCreateStatus) {
        this.$message({
          type: 'warning',
          message:
            '已有AI正在生成中，等待生成内容结束或F5刷新页面再次点击AI生成!'
        });
        return;
      } else {
        this.aiCreateStatus = true;
        // this.currentEdit = true;
        let textEl = document.querySelectorAll('.AIBtn'); // 获取要添加省略号的元素
        textEl.forEach((item) => {
          item.classList.add('AILoading'); // 添加类名，启动动画效果
        });
      }

      //获取问题
      const name =
        this.$route.query.name != undefined ? this.$route.query.name : '';

      const questionRes1 = await this.reqGetQuestionbyId(this.firstQuestionId);
      const questionRes2 = await this.reqGetQuestionbyId(this.secondQuestionId);
      this.chatKey1 = questionRes1.data.questionContent.replace(/{}/g, name);
      this.chatKey2 = questionRes2.data.questionContent.replace(/{}/g, name);

      //同时发送两个问题给chatGPT
      this.firstMessages.push({
        role: 'user',
        content: this.chatKey1
      });
      this.secondMessages.push({
        role: 'user',
        content: this.chatKey2
      });
      const agentData1 = {
        userId: '',
        userName: '',
        messages: this.firstMessages
      };
      const agentData2 = {
        userId: '',
        userName: '',
        messages: this.secondMessages
      };
      this.firstMessages = [];
      this.secondMessages = [];
      this.sendMsg1 = JSON.stringify(agentData1);
      this.sendMsg2 = JSON.stringify(agentData2);

      this.$set(this.firstExtendContent, this.firstExtendContent.length, '');
      this.$set(this.secondExtendContent, this.secondExtendContent.length, '');

      this.$refs.child1.send(
        this.sendMsg1,
        this.initMessageBackForFirst,
        this.wsError
      );
      this.$refs.child2.send(
        this.sendMsg2,
        this.initMessageBackForSecond,
        this.wsError
      );

      this.$message.success({
        message: 'AI生成内容中...',
        offset: '400'
      });
      addLog({ logType: '10' });
    },
    reqGetQuestionbyId(questionId) {
      return homepageQuestion({ questionId });
    },
    wsError() {
      // if (this.isStoped) {
      //   this.isContinue = false;
      // } else {
      //   this.isContinue = true;
      // }
      //console.log("连接失败，请重试");
    }
  },
  components: {
    Websocket
  }
};
</script>

<style lang="scss" scoped>
.unitWrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  // height: 100px;
  .unitTop {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(260deg, #48a8ff 0%, #1470fa 100%);
    border-radius: 8px 8px 0px 0px;
    opacity: 0.87;
    padding: 10px 18px;
    .unitTitleContainer {
      display: flex;
      align-items: center;
      .unitFlag {
        width: 5px;
        height: 15px;
        background: #ffffff;
        border-radius: 3px;
        margin-right: 8px;
      }
      .unitTitle {
        height: 25px;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        letter-spacing: 0.3px;
        color: #ffffff;
        line-height: 25px;
      }
    }

    .saveBtns {
      display: flex;
      height: 32px;
      align-items: center;
      justify-content: center;
      padding-right: 10px;
      .contentItemEditAndAIBtn {
        line-height: 32px;
        margin: 0 10px 0 15px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        display: flex;
        align-items: center;
        cursor: pointer;
        img {
          width: 22px;
          height: 22px;
        }
      }
      .saveEditBtn {
        width: 57px;
        height: 26px;
        color: #3674ff;
        background-color: #fff;
        border-radius: 4px;
        justify-content: center;
      }
    }
  }
  .unitContent {
    // height: 280px;
    display: flex;
    flex-wrap: wrap;
    background: #ffffff;
    border-radius: 0px 0px 8px 8px;
    border: 1px solid #c8cee9;
    &.colunmDirection {
      flex-direction: column;
    }
    .firstItem {
      display: flex;
      justify-content: center;
      // align-items: center;
      flex: 1;
      .itemForDisplay {
        flex: 1;
        max-width: auto;
        padding: 77px 24px;
        margin-left: 20px;
        &.inEdit {
          max-width: 50%;
          margin-left: 14px;
        }
        .firstChildList {
          display: grid;
          grid-column-gap: 20px;
          grid-row-gap: 40px;
          grid-template-columns: repeat(2, 1fr);
          // width: 300px;
          .firstChildItem {
            display: flex;
            .firstChildItemImg {
              margin-right: 20px;
            }
            .firstChildInfo {
              display: flex;
              flex-direction: column;
              .firstChildDescription {
                font-size: 15px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #555555;
                line-height: 24px;
                margin-bottom: 6px;
              }
              .firstChildValue {
                height: 24px;
                font-size: 16px;
                font-family: PingFang-SC-Bold, PingFang-SC;
                font-weight: bold;
                color: #333333;
                line-height: 24px;
              }
              .firstChildInput {
                width: 123px;
                // height: 32px;
                background: #eeeeee;
                border-radius: 2px;
              }
            }
          }
        }
      }
      .itemForEdit {
        flex: 1;
        .editBoxRight {
          flex: 1;
          padding: 55px 16px 12px 16px;
          font-size: 15px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #4b6aaf;
          line-height: 27px;
          position: relative;
          border-radius: 0px 6px 6px 0px;
          min-height: 300px;
          padding-bottom: 20px;
          .extendsItem {
            position: relative;
            padding-bottom: 35px;
            padding: 12px 0px;
            .replaceByOne {
              display: flex;
              justify-content: flex-end;
              position: relative;
              bottom: 0;
              right: 14px;
              cursor: pointer;
              color: #4880ff;
            }
          }
          &.inEdit {
            background: #f5f9ff;
          }
        }
      }
    }
    .secondItem {
      display: flex;
      justify-content: center;
      // align-items: center;
      flex: 1;
      .itemForDisplay {
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 1;
        width: 50%;
        margin-left: 27px;
        padding: 0px 0px;
        min-width: 422px;
        // margin-left: 51px;
        flex-direction: column;
        .editTips {
          position: relative;
          font-size: 14px;
          font-family: PingFang-SC-Bold, PingFang-SC;
          color: #aaa;
          line-height: 28px;
          padding-bottom: 5px;
          padding-top: 8px;
          bottom: -20px;
        }
      }
      .h100 {
        min-width: 422px;
        height: 312px;
        flex: 1;
      }
      .itemForEdit {
        flex: 1;
        // max-width: 50%;
        .editBoxRight {
          flex: 1;
          padding: 12px 16px 12px 16px;
          font-size: 15px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #4b6aaf;
          line-height: 27px;
          position: relative;
          border-radius: 0px 6px 6px 0px;
          min-height: 300px;
          padding-bottom: 20px;
          .extendsItem {
            position: relative;
            padding-bottom: 35px;
            padding: 12px 16px 12px 16px;
            .replaceByOne {
              display: flex;
              justify-content: flex-end;
              position: relative;
              bottom: 0;
              right: 14px;
              cursor: pointer;
              color: #4880ff;
            }
          }
          &.inEdit {
            background: #f5f9ff;
          }
        }
      }
    }
  }
  ::v-deep .el-input__inner {
    height: 32px;
    background: #eeeeee;
    border-radius: 2px;
    font-size: 16px;
    font-family: PingFang-SC-Bold, PingFang-SC;
    font-weight: bold;
    color: #333333;
    line-height: 24px;
    outline: none;
  }
}
</style>
